<?php

class answers extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->model('answers_model');
    }

    public function evaluateAnswer($answers) {
        $numberOfCorrect = 0;
        $score = 0.0;

        foreach ($answers as $key => $value) {
            $cleanKey = substr($key , 7, strlen($key));
            $correct = $this->answers_model->getCorrectAnswers($cleanKey);
            $value = trim(strtolower($value));
            $correct = trim(strtolower($correct));
            if ($correct == $value) {
                $numberOfCorrect+=1;
            }
        }
        $score = ($numberOfCorrect / count($answers)) * 100;
        $score = number_format($score, 2, '.', '');
        
        return $score;
    }

    public function getExamDetails() {
        foreach ($_POST as $key => $value) {
            if ($key == 'timerValue') {
                if ($value != '00:00:00') {
                    $_SESSION['time'] = $value;
                }
            } else {
                $answers[$key] = $value;
            }
        }

        $score = $this->evaluateAnswer($answers);
        $hasPassed = $score > 79 ? 'pass' : 'fail';
        
        
        if (isSet($_SESSION['type'])){
            unset($_SESSION['type']);
            $location = base_url('progress/diagnosticUpdate/' . $hasPassed . '/');
            redirect($location);
        } else {
            $location = base_url('progress/index/'.$score.'');
            redirect($location);
        }
    }

}

?>
